package com.ebupt.migu.music.autoTri.Service.Impl;

import com.ebupt.migu.music.autoTri.Entity.PushBean;
import com.ebupt.migu.music.autoTri.Service.PushListService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tz
 */
@Slf4j
@Service
public class PushListServiceImpl implements PushListService {

    @Value("${push.sys_url}")
    private String sysUrl;

    @Override
    public Map<String, Object> pushDeal(Map<String, Object> param) {
        //用gson获取对应参数
        Gson gson = new Gson();
        Map m = (Map) gson.fromJson(param.get("constructionJson").toString(),Map.class).get("constructionJson");
        List<Map<String, String>> list = (List<Map<String, String>>) m.get("triggerList3");
        //替换系统默认路径
        for(Map<String,String> map:list){
            map.put("pushUrl", "1".equals(map.get("smsUrlType")) ? sysUrl : map.get("pushUrl"));
        }
        //处理后结果集
        Map<String,Object> reMap = beanToMap(new PushBean());
        //遍历list -- stream处理方式
        reMap.replaceAll(
                (k, v) -> list.stream().map(
                        e -> "".equals(e.get(k)) ? " " : e.get(k))
                            .collect(Collectors.joining("^")));
        //多模板数量
        reMap.put("templateNum",list.size());
        return reMap;
    }

    @Override
    public Map<String, Object> manualDeal(Map<String, Object> param) {
        Gson gson = new Gson();
        List<Map<String, String>> list = (List) gson.fromJson(param.get("triggerList").toString(),List.class);
        //替换系统默认路径
        for(Map<String,String> map:list){
            map.put("pushUrl", "1".equals(map.get("smsUrlType")) ? sysUrl : map.get("pushUrl"));
        }
        //随机取模板
        int rand = (int)(0+Math.random()*list.size());
        Map<String,String> m = list.get(rand);
        Map<String,Object> reMap = beanToMap(new PushBean());
        reMap.replaceAll((k, v) -> m.get(k));
        return reMap;
    }

    /**
     * JavaBean转换Map
     * @param object
     * @return
     */
    private static Map<String, Object> beanToMap(Object object) {
        Map<String, Object> result = new HashMap<>();
        //获得类的的属性名数组
        Field[] fields = object.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = new String(field.getName());
                result.put(name, field.get(object));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
